﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using LEEAAttendanceControl.Web;
using LEEAAttendanceControl.General;
using LEEAAttendanceControl.Web.Services;

using System.ServiceModel.DomainServices.Client;
using LEEAAttendanceControl.AttendanceReference;
using System.Collections.ObjectModel;

namespace LEEAAttendanceControl.Views
{
    public partial class LocationEdit : ChildWindow
    {
        LEEAContext context = new LEEAContext();

        Location location = new Location();

        public LocationEdit()
        {
            InitializeComponent();
        }

        public LocationEdit(string title)
        {
            Title = title;

            InitializeComponent();
        }

        public void LoadData(int id)
        {
            AttendanceServiceClient proxy=General.General.GetProxy();
            proxy.GetDevicesCompleted+=(s1,e1)=>{
                cboDevices.ItemsSource = e1.Result;
                context.Load(context.GetLocationByIdQuery(id), OnLocationLoadCompleted, null);
            };
            proxy.GetDevicesAsync();
        }
        
        private void OnLocationLoadCompleted(LoadOperation load)
        {
            location = (Location)load.Entities.FirstOrDefault();

            if (location == null)
            {
                location = new Location();
                context.Locations.Add(location);
            }

            DataContext = location;
            //cboDevices.SelectedValue = location.DeviceId.ToString();
        }

        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            context.SubmitChanges(OnChangedSubmitted, null);
        }

        protected void OnChangedSubmitted(SubmitOperation so)
        {
            if (so.HasError)
            {
                so.MarkErrorAsHandled();
            }
            else
            {
                MessageBox.Show(ApplicationStrings.GeneralSave, ApplicationStrings.GeneralSave, MessageBoxButton.OK);
                this.Close();
            }
        }
    }
}

